package com.cloudspace.jindun.activity.xiaoxi;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.adapter.TopicAdatper;
import com.cloudspace.jindun.dao.ContactPerson;
import com.cloudspace.jindun.model.CommonResult;
import com.cloudspace.jindun.model.Friends;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class TopicLXRActivity extends CustomTitleBaseActivity {
    public static final String TAG = TopicLXRActivity.class.getSimpleName();

    @Bind(R.id.topiclxr_iv_back)
    ImageView mTopiclxrIvBack;
    @Bind(R.id.topiclxr_text_title_chuanjian)
    TextView mTopiclxrTextTitleChuanjian;
    @Bind(R.id.topiclxr_lv_thirdOrig)
    ListView mTopiclxrLvThirdOrig;
    @Bind(R.id.topiclxr_text_title)
    TextView mTopiclxrTextTitle;

    private TopicAdatper thirdAdapter;
    private List<Friends.DataBean> thirdPersons = new ArrayList<>();
    private String title, channelType;
    int isbut;
    private List<String> userIDs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_topic_lxr, false);
        ButterKnife.bind(this);
        requestData();
        initData();
    }

    private void initData() {
        thirdAdapter = new TopicAdatper(this);
        mTopiclxrLvThirdOrig.setAdapter(thirdAdapter);
        title = getIntent().getStringExtra("title");
        isbut = getIntent().getIntExtra("isbut", 1);
        if (isbut == 2) {
            mTopiclxrTextTitle.setText(getResources().getString(R.string.create_groupchat));
        }

        switch (isbut) {
            case 1:
                channelType = "0001";
                break;
            case 2:
                channelType = "0002";
                break;
        }


    }

    @OnClick({R.id.topiclxr_iv_back, R.id.topiclxr_text_title_chuanjian})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.topiclxr_iv_back:
                finish();
                break;
            case R.id.topiclxr_text_title_chuanjian:
                addContacts();
                break;
        }
    }

    private void requestData() {
        OkHttpUtils.get()
                .url(YXHttpUrl.SERVER_URI + "phone/" + UserSessionManager.getInstance().getUserId() + "/isPer")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            Gson gson = new Gson();
                            Friends friends = gson.fromJson(response, Friends.class);
                            if (friends.getStatus() == 200 && !ObjUtil.isEmpty(friends.getData())) {
                                thirdAdapter.setDatas(friends.getData());
                                thirdPersons = friends.getData();
                            }
                        }
                    }
                });
    }

    private String friendListStr;

    //添加联系人
    private void addContacts() {
        if (ObjUtil.isEmpty(thirdAdapter)
                || ObjUtil.isEmpty(thirdAdapter.getChecked())
                || ObjUtil.isEmpty(thirdPersons)) {
            return;
        }

        List<Integer> checked = thirdAdapter.getChecked();
        final List<ContactPerson> checkPerson = new ArrayList<ContactPerson>();


        friendListStr = "";
        for (int i = 0; i < thirdPersons.size(); ++i) {
            if (checked.get(i) == 1 && !ObjUtil.isEmpty(thirdPersons.get(i))) {
                userIDs.add(thirdPersons.get(i).getUserId());
                //   checkPerson.add(Person.contructContactPerson(thirdPersons.get(i)));
                friendListStr = friendListStr + thirdPersons.get(i).getUserId() + ",";
            }
        }
        if (friendListStr.contains(",")) {
            friendListStr = friendListStr.substring(0, friendListStr.length() - 1);
        }

        if (TextUtils.isEmpty(friendListStr)) {
            ToastMaker.showToastShort(R.string.group_chat_addmember_empty);
            return;
        }

        switch (isbut) {
            case 1:
                createTopic(YXHttpUrl.XX_JRHT, channelType, title,
                        UserSessionManager.getInstance().getUserId(),
                        friendListStr);

                break;
            case 2:
                if (userIDs != null && userIDs.size() != 0) {
                    createGroupChat(YXHttpUrl.XX_CJHT,
                            title,
                            UserSessionManager.getInstance().getUserId(),
                            friendListStr);
                }
                break;
        }

    }

    private void createGroupChat(String url,
                                 String channelName,
                                 String chaCrePer,
                                 String listLinkPer) {
        OkHttpUtils.post()
                .url(url)
                .addParams("channelName", channelName)
                .addParams("chaCrePer", chaCrePer)
                .addParams("listLinkPer", listLinkPer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.create_groupchat_fail);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        handleCreateResult(response);
                    }
                });
    }

    private void handleCreateResult(String response) {
        if (!TextUtils.isEmpty(response)){
            Gson gson = new Gson();
            CommonResult result = gson.fromJson(response, CommonResult.class);
            if (result != null && result.status == 200) {
                ToastMaker.showToastShort(R.string.create_groupchat_success);
                finish();
            }else{
                ToastMaker.showToastShort(R.string.create_groupchat_fail);
            }
        }
    }

    private void createTopic(String url, String channelType,
                             String channelName, String chaCrePer,
                             String listLinkPer) {
        OkHttpUtils.post()
                .url(url)
                .addParams("channelType", channelType)
                .addParams("channelName", channelName)
                .addParams("chaCrePer", chaCrePer)
                .addParams("listLinkPer", listLinkPer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.create_groupchat_fail);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        handleCreateResult(response);
                    }
                });
    }
}
